package com.xiaoyi.common.security;

import com.xiaoyi.common.exception.UserCountLockException;
import com.xiaoyi.entity.SysUser;
import com.xiaoyi.service.SysUserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 小易
 * @version 1.0
 * @description TODO
 * @date 2022/12/6 16:19
 */
@Component
public class MyUserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private SysUserService userService;

    /**
     * @description 重写通过用户名加载用户信息方法
     * @param username 用户名
     * @return org.springframework.security.core.userdetails.UserDetails
     * @author 小易
     * @date 2022/12/19 15:47
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = userService.getByUsername(username);
        if (sysUser == null) throw new UsernameNotFoundException("用户名或密码错误！");
        else if ("1".equals(sysUser.getStatus())) throw new UserCountLockException("该用户帐号异常，已禁止登录！");
        return new User(sysUser.getUsername(), sysUser.getPassword(), getUserAuthority(sysUser.getId()));
    }

    /**
     * @description 通过id获取权限列表
     * @param userId 用户id
     * @return java.util.List<org.springframework.security.core.GrantedAuthority>
     * @author 小易
     * @date 2022/12/19 15:47
     */
    public List<GrantedAuthority> getUserAuthority(long userId) {
        String authority = userService.getUserAuthorityInfo(userId);
        return AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
    }
}
